#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@File ：UserController.py
@Author ：zqy
@Email : zqingy@work@163.com
@note: 用户接口视图
"""

from flask import session, g
from flask_restx import Namespace, Resource

from application.Parser import with_parser
from application.Parser.UserParser import UserValidator
from application.controller import register_crud_model
from application.logic.UserLogic import UserLogic
from application.util.ResponseUtil import ResponseUtil

user_ns = Namespace("user", description="用户相关接口")
user_parser: UserValidator = UserValidator

register_crud_model(
    ns=user_ns,
    logic_cls=UserLogic,
    parser=user_parser,
    roles=["superuser"],
    route="",
    id_type="int",
    include_operations=["list", "delete"]
)


@user_ns.route("/register")
class RegisterResource(Resource):
    p = user_parser.register()

    @with_parser(p)
    def post(self):
        """注册"""
        UserLogic.register(self.p.parse_args())
        return ResponseUtil(message="注册成功").success()


@user_ns.route("/login")
class LoginResource(Resource):
    p = user_parser.login()

    @with_parser(p)
    def post(self):
        """登录"""
        return ResponseUtil(data=UserLogic.login(self.p.parse_args())).success()


@user_ns.route("/logout")
class LogoutResource(Resource):
    def post(self):
        """退出登录"""
        UserLogic.logout()
        session.clear()
        return ResponseUtil().success()


@user_ns.route("/now_user_info")
class NowUserInfoResource(Resource):
    def get(self):
        """获取当前用户信息"""
        return ResponseUtil(data=UserLogic.now_user_info(user_id=session.get("user"))).success()


@user_ns.route("/change_password")
class ChangePasswordResource(Resource):
    p = user_parser.change_password()

    @user_ns.expect(p)
    def post(self):
        """更改密码"""
        UserLogic.change_password(self.p.parse_args())
        return ResponseUtil(message="修改密码成功").success()


@user_ns.route("")
class UserResource(Resource):
    p = user_parser.put()

    @user_ns.expect(p)
    def put(self,):
        """修改当前用户信息"""
        return ResponseUtil(data=UserLogic.update_by_id(g.user.id, data=self.p.parse_args())).success()
